<?php
class AccountsController extends AppController {

	var $name = 'Accounts';
	
	function beforeFilter() {
		parent::beforeFilter();	
		//todo: Kell ez? $this->Auth->userScope = array('User.active' => 1);	//deleted and not activated users denied
		if($this->data){
			App::import('Sanitize');
			$this->data['Account']['username'] = Sanitize::paranoid($this->data['Account']['username'], array('@', '-', '_', '.'));
			$this->data['Account']['pass'] = isset($this->data['Account']['pass']) ? Sanitize::html($this->data['Account']['pass']) : null;
		}
		$this->Auth->allow('addfacebook',
								 'removefacebook',
								 'facebookGetAuthorizeLink'
								 );	//ezekhez nem kell élő session
	}
	
	function isAuthorized(){
		if($this->Auth->user('group_id') == $this->Session->read('Settings.adminPermission')){		//admin jogosultságú júzerek
			return true;
		}
		else{		//free user / premium user / business user		//élő session kell hozzájuk
			if(in_array($this->action, array(
														'index',
														'add',
														'edit',
														'remove',
														'addTwitter'
														))){
				return true;
			}
		}
		return false;		//minden más tiltva
	}

	function add() {
		//first check if the user could create a new account or not
		$this->Account->User->Group->id = $this->Auth->user('group_id');
		$this->Account->User->Group->recursive = 0;
		$maxAccounts = $this->Account->User->Group->read('max_accounts');
		$presentAccounts = $this->Account->find('count',
											  array(
												'conditions' => array('user_id' => $this->Auth->user('id'))
												));
		if($maxAccounts['Group']['max_accounts'] > $presentAccounts){
			if (!empty($this->data)) {
				if($this->data['Account']['community_id'] == 3){		//hardcoded
					//facebook so we drop the user to facebook
					$this->redirect(array('action' => 'addfacebook'));
				}
				elseif($this->data['Account']['community_id'] == 2){		//hardcoded
					//twitter so we drop the user to twitter
					$this->redirect(array('action' => 'addTwitter'));
				}
				if($this->data['Account']['community_id'] == 4){		//hardcoded
					//myspace
					$this->redirect(array('action' => 'addMyspace'));
				}
				$this->Account->create();
				$this->data['Account']['user_id'] = $this->Auth->user('id');
				$this->data['Account']['pass'] = $this->_encodePass($this->data['Account']['pass']);
				if ($this->Account->save($this->data)) {
					$this->Session->setFlash(__('The Account has been saved', true));
					//ping küldése
					//todo: facebooknál máshogyan kell kezelni
					$this->Session->write('ping', array(
						'message' => __('I have registered myself to SociALL', true) . ' http://sociall.cc',
						'account_id' => $this->Account->id
						));
					$this->redirect(array('controller' => 'messages', 'action'=>'index'));
				} else {
					$this->Session->setFlash(__('The Account could not be saved. Please, try again.', true));
				}
			}
			$_communities = $this->Account->Community->find('all');
			$communities = array();
			foreach($_communities as $c){
				if($c['Community']['experimental'] && $this->Auth->user('active') == 2)
					$communities[$c['Community']['id']] = $c['Community']['name'] . __(' (experimental)', true);
				elseif(!$c['Community']['experimental'])
					$communities[$c['Community']['id']]  = $c['Community']['name']; 
			}
			$this->set('communities', $communities);
		}
		else{
			$this->set('warning', 'warning_upgrade');
		}
	}

	function edit() {
		$id = $this->data['Account']['id'];
		$owner = $this->Account->find('all',
									array(
										'conditions' => array('Account.id' => $id),
										'fields' => array('User.id')
									));
		//debug($owner);
		//is this account editable by this user?
		if($owner[0]['User']['id'] != $this->Auth->user('id'))
			$this->redirect('/');
//debug($this->data);
		if (!empty($this->data)){
			if($this->data['Account']['pass_change'] != $this->data['Account']['pass_confirm']){
				$this->Session->setFlash(__('Passwords are not the same. Please try again', true));
			}
			elseif($this->data['Account']['pass_change'])
				$this->data['Account']['pass'] = $this->_encodePass($this->data['Account']['pass_change']);
			$this->Account->id = $id;
//debug($this->data);
			if($this->Account->save($this->data)) {
				$this->Session->setFlash(__('The Account has been saved', true));
				//if iwiw is changed we should update the session
				$_account = $this->Account->find('first', array(
															'conditions' => array('Account.id' => $id)
															));
				if($_account['Community']['id'] == 1){	//todo: HC iwiw.id
					$this->Session->del('iwiwSid.acc_'.$id);
				}
				
			}
			else {
				$this->Session->setFlash(__('The Account could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Account->read(null, $id);
		}
		/*$users = $this->Account->User->find('list');
		$communities = $this->Account->Community->find('list');
		$this->set(compact('users','communities'));*/
		$this->redirect(array('controller' => 'users', 'action'=>'edit'));
	}

	function remove($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Account', true));
			$this->redirect(array('controller' => 'users', 'action'=>'edit'));
		}
		if ($this->Account->del($id)) {
			$this->Session->setFlash(__('Account deleted', true));
			$this->redirect(array('controller' => 'users', 'action'=>'edit'));
		}
	}


	function admin_index() {
		$this->Account->recursive = 0;
		$this->set('accounts', $this->paginate());
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->data['Account']['pass'] = $this->_encodePass($this->data['Account']['pass']);
			$this->Account->create();
			if ($this->Account->save($this->data)) {
				$this->Session->setFlash(__('The Account has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Account could not be saved. Please, try again.', true));
			}
		}
		$users = $this->Account->User->find('list');
		$communities = $this->Account->Community->find('list');
		$this->set(compact('users', 'communities'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Account', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Account->save($this->data)) {
				$this->Session->setFlash(__('The Account has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Account could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Account->read(null, $id);
		}
		$users = $this->Account->User->find('list');
		$communities = $this->Account->Community->find('list');
		$this->set(compact('users','communities'));
	}

	function admin_remove($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Account', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Account->del($id)) {
			$this->Session->setFlash(__('Account deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}
	
/*
 * Authorize SociALL to communicate with Facebook on behalf of the current user
 * The user will redirected to facebbok and there he gives permissions, so we do not need any username or pass
 * this is the Post-Authorize Callback URL http://wiki.developers.facebook.com/index.php/Post-Authorize_URL
 * the user will not be redirected here on authrization process, this method just would get facebook post parameters like fb_sig_user, etc
 * after the authentication process is finished the user will be redirected to Canvas Callback URL: http://sociall.cc
 *
 * @param string $setpermissions if 'setpermissions' the user is redirected here after authorized sociall
 * 										so we have to send the user back to facebook to get extended permissions
*/
	function addfacebook($setpermissions = false){
		App::import('Vendor', 'facebook');
		$app_id = $this->Option->field('value', array('name' => 'facebook_app_id'));
		$api_key = $this->Option->field('value', array('name' => 'facebook_api_key'));
		$secret = $this->Option->field('value', array('name' => 'facebook_secret_key'));
		$facebook = new Facebook($api_key, $secret);
		//if the user is not loggen in to facebook he will be redirected to login and authenticate sociall. If the user is logged in we just get the user id
		$facebookUserId = $facebook->require_login();
		//vagy: $facebookUserId = $facebook->require_add();
		
		if($setpermissions == 'setpermissions' || $facebookUserId){
			//giving a link to the user by what he could give us the needed permissions
			//the user redirected here after authorized sociall
			
			/*
			$this->params[url] => Array
	        (
            [ext] => html
            [url] => accounts/addfacebook/setpermissions
            [auth_token] => ef59da3b2d9b2569a85ffe7272bed968
            [next] => http://sociall.cc/accounts/addfacebook/
            [installed] => 1
	        )
			*/
			
			//permissions: read_stream, offline_access, status_update

			/*$authorizeLink = 'http://www.facebook.com/authorize.php?api_key='.$api_key.'&v=1.0';
			$link_publish_stream = urlencode($authorizeLink . '&ext_perm=publish_stream');//&next='.$link_home);
			$link_read_stream = urlencode($authorizeLink . '&ext_perm=read_stream&next='.$link_publish_stream.'&next_cancel='.publish_stream);
			$link_offline_access = $authorizeLink . '&ext_perm=offline_access&next='.$link_read_stream.'&next_cancel='.$link_read_stream;
			$link_getPermissions = $link_offline_access;*/
			$this->set('facebookLogin', $this->facebookGetAuthorizeLink($api_key));
			
			/*
			page publish?
			http://www.facebook.com/connect/prompt_permissions.php?api_key=YOUR_API_KEY&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=popup&ext_perm=read_stream,publish_stream&enable_profile_selector=1&extern=1&fbconnect=1
			*/
			
			$userId = $facebook->get_loggedin_user();
			$user = $facebook->api_client->users_getInfo($userId, 'name');
			
			$account = array('Account' => array(
														'user_id' =>  $this->Auth->user('id'),
														'community_id' => 3,	//hardcoded
														'username' => $user[0]['name'],
														'pass' => $facebook->api_client->session_key,
														'extras' => serialize(array('auth' => 'auth', 'userId' => $userId)),
														'gettimeline' => 1
														)
									);
			$this->Account->save($account);
			/*$this->log('SociaLL user id: ' . $this->Auth->user('id'), LOG_DEBUG);
			$session_key = $facebook->api_client->session_key;
			$uid = $facebook->get_loggedin_user();
			$this->log('Facebook user id: ' . $uid, LOG_DEBUG);
			$this->log('Facebook session_key: ' . $session_key, LOG_DEBUG);*/
		}
	}

/*
* Get link what is needed for Facebook authorization
*/
	function facebookGetAuthorizeLink($api_key){
		$authorizeLink = 'http://www.facebook.com/authorize.php?api_key='.$api_key.'&v=1.0';
		$link_publish_stream = urlencode($authorizeLink . '&ext_perm=publish_stream');
		$link_read_stream = urlencode($authorizeLink . '&ext_perm=read_stream&next='.$link_publish_stream.'&next_cancel='.$link_publish_stream);
		$link_offline_access = $authorizeLink . '&ext_perm=offline_access&next='.$link_read_stream.'&next_cancel='.$link_read_stream;
		$link_getPermissions = $link_offline_access;
		return $link_getPermissions;
	}
	
	function removefacebook(){
		//called if a user removes sociall from his facebook application gets POST
		$this->log('SociALL removed: ' . print_r($this->params['form'], true), LOG_DEBUG);
		//todo: ki kell venni az accounts táblából mert ha vissza is engedélyezi más session keyt fog kapni
		/*
	    [form] => Array
        (
            [fb_sig_uninstall] => 1
            [fb_sig_locale] => hu_HU
            [fb_sig_in_new_facebook] => 1
            [fb_sig_time] => 1247313425.4863
            [fb_sig_added] => 0
            [fb_sig_user] => 1243160898
            [fb_sig_api_key] => 8aca***9df9fa2
            [fb_sig_app_id] => 91242048462
            [fb_sig] => b9e5***edc2c84
        )
		*/
	}
	
/*
 * Authorize SociALL to communicate with Twitter on behalf of the current user via oAuth
 * from: https://docs.google.com/View?docID=dcf2dzzs_2339fzbfsf4
*/
	function addTwitter($verify = false){
		App::import('Vendor', 'twitterOAuth', array('file' => 'twitterOAuth.php'));
		
		$consumer_key = $this->Option->field('value', array('name' => 'twitter_consumer_key'));
		$consumer_secret = $this->Option->field('value', array('name' => 'twitter_secret_key'));

		if(!$verify){
			$twitterOAuth = new TwitterOAuth($consumer_key, $consumer_secret);
		
			$tokens = $twitterOAuth->getRequestToken();
			//debug($tokens);
			/*
			Array(
		    [oauth_token] => qiC5frc7Oc9***Sk0xpGlUxRQ
		    [oauth_token_secret] => F6yMnTA***Wwv92g
			)
			*/
			$request_link = $twitterOAuth->getAuthorizeURL($tokens);
			$this->Session->write('Twitter.OAuth.token', $tokens['oauth_token']);
			$this->Session->write('Twitter.OAuth.token_secret', $tokens['oauth_token_secret']);
			$this->redirect($request_link);
			//debug($request_link);
			/*
			 https://twitter.com/oauth/authorize?oauth_token=qiC5frc7Oc9***Sk0xpGlUxRQ
			 we should redirect the user here
		 
			 after she allow us she will be redirected to callback url?oauth_token=qiC5frc7Oc9G***xpGlUxRQ
					 */
		}
		if($verify){
			$twitterOAuth = new TwitterOAuth($consumer_key, $consumer_secret, $this->Session->read('Twitter.OAuth.token'), $this->Session->read('Twitter.OAuth.token_secret'));
			$accessTokens = $twitterOAuth->getAccessToken();
			/*
			Array(
				[oauth_token] => 12460092-N***518MXuT5lFxPRhfc1Sli4
				[oauth_token_secret] => v7jT6C***zRQ5uBCPGwI5Eyc
				[user_id] => 12460092
				[screen_name] => rrd)
			*/
			$this->Session->write('Twitter.OAuth.token', $accessTokens['oauth_token']);
			$this->Session->write('Twitter.OAuth.token_secret', $accessTokens['oauth_token_secret']);
			$account = $this->Account->find('first',
													  array(
															'conditions' => array(
																						'Account.community_id' => 2,		//todo: HC
																						'Account.username' => $accessTokens['screen_name']
																						),
															'fields' => array('id'),
															'recursive' => -1
													  )
													  );
			$this->Account->id = $account['Account']['id'];
			$account = array('Account' => array(
														'user_id' =>  $this->Auth->user('id'),
														'community_id' => 2,	//hardcoded
														'username' => $accessTokens['screen_name'],
														'pass' => 'auth',
														'extras' => serialize(array(
																					'oauth_token' => $this->_encodePass($accessTokens['oauth_token']),
																					'oauth_token_secret' => $this->_encodePass($accessTokens['oauth_token_secret']))),
														'gettimeline' => 1
														)
									);
			$this->Account->save($account);
			$this->redirect(array('controller' => 'users', 'action' => 'edit'));
		}
	}

/*
 * Authorize SociALL to communicate with MySpace on behalf of the current user via MySpaceid-php-sdk
 * 
*/
	function addMyspace(){
		App::import('Vendor', 'myspaceid-php-sdk');
		
		$ms_key = $this->Option->field('value', array('name' => 'myspace_consumer_key'));
		$ms_secret = $this->Option->field('value', array('name' => 'myspace_consumer_secret'));;
		
		$ms = new MySpace($ms_key, $ms_secret);
$tok = $ms->getRequestToken("http://www.yanguchong.com/samples/myspaceid-oauth/index.php?f=callback");
		if (!isset($tok['oauth_token'])
		      || !is_string($tok['oauth_token'])
		      || !isset($tok['oauth_token_secret'])
		      || !is_string($tok['oauth_token_secret'])) {
		   echo "ERROR! MySpace::getRequestToken() returned an invalid response. Giving up.";
		   exit;
		}
		debug($tok);
		//header("Location: ".$ms->getAuthorizeURL($token));

		
		
		//$this->Account->save($account);
		//$this->redirect(array('controller' => 'users', 'action' => 'edit'));
	}

}
?>
